package net;

import java.util.ArrayList;

import model.Location;
import model.TockChat;
import model.TockGame;
import model.TockConstants;

public class TockServerHandler implements TockConstants {
	
	private String name;
	private TockGame game;
	private TockChat chat;
	
	public String getName() {return name;}
	public TockGame getGame() {return game;}
	public TockChat getChat() {return chat;}
	
	public TockServerHandler(int players, String name) {
		game = new TockGame(players);
		chat = new TockChat();
		this.name = name;
	}
	
	public void handleChat(TockPacket packet) {
		String sender = packet.getSender();
		String message = packet.getMessage();
		
		if ((packet.getSender() != "") && (packet.getMessage() != "")) {
				chat.newMessage(sender, message);
		} else System.out.println("SERVER: Error, bad chat packet.");
	}
	
	public void handleMove(TockPacket packet) {
		String sender = packet.getSender();
		int card = packet.getCard();
		Location pieceSource = packet.getPieceSource();
		Location pieceDest = packet.getPieceDest();
		int movePacketType = packet.getMovePacketType();
		ArrayList<Location> sevenLocations = packet.getSevenMoves();
		
		if ((sender != "") && (card != -1)) {
			int result = game.makeMove(sender, card, pieceSource, pieceDest, movePacketType, sevenLocations);
			
			//--- Set the last card if the move was successful
			if (result == MOVE_ERROR_NONE) {
				game.setLastCard(""+card);
			}
			if (result != 0) {
				System.out.println("SERVER: Game Error, Error-Code = " + result);
			}
		} else System.out.println("SERVER: Error, bad move packet.");
	}
	
	public void handleRegister(TockPacket packet) {
		String sender = packet.getSender();
		if (sender != " ") {
			game.register(sender);
			chat.addUser(sender);
		} else System.out.println("SERVER: Error, bad register packet.");
	}
	
	public void handleExit(TockPacket packet) {
		String sender = packet.getSender();
		if (sender != " ") {
			game.unregister(sender);
		} else System.out.println("SERVER: Error, bad exit packet.");
	}
	
	public void handleSit(TockPacket packet) {
		String sender = packet.getSender();
		if (sender != " ") {
			game.sitPlayer(sender);
		} else System.out.println("SERVER: Error, bad sit packet.");
	}
	
	public void handleStand(TockPacket packet) {
		String sender = packet.getSender();
		if (sender != " ") {
			game.standPlayer(sender);
		} else System.out.println("SERVER: Error, bad stand packet.");
	}
}
